/**
 * 预约服务增强版 - 支持Mock数据fallback
 */

import { get, post, del } from './request.js'

class AppointmentService {
  constructor() {
    this.mockMode = false
  }

  // 检测API连通性
  async checkApiConnectivity() {
    try {
      const response = await get('/health', {}, { timeout: 3000 })
      return response && response.status === 'ok'
    } catch (error) {
      console.log('API连通性检查失败，将使用Mock模式')
      return false
    }
  }

  // 获取医院列表 (支持Mock fallback)
  async getHospitals(params = {}) {
    try {
      const response = await get('/v1/appointment/hospitals', params)
      return response
    } catch (error) {
      console.warn('获取医院列表失败，使用Mock数据:', error)
      
      const mockHospitals = [
        {
          id: 'h001',
          name: '河北省保定市莲池区保定市第一医院',
          address: '河北省保定市莲池区东风东路572号',
          phone: '0312-5976120',
          level: '三甲',
          city: '保定',
          distance: 0.5
        },
        {
          id: 'h002',
          name: '保定市人民医院',
          address: '保定市竞秀区长城北大街320号',
          phone: '0312-5976666',
          level: '三甲',
          city: '保定',
          distance: 1.2
        },
        {
          id: 'h003',
          name: '保定市中医院',
          address: '保定市莲池区裕华东路530号',
          phone: '0312-5976888',
          level: '三甲',
          city: '保定',
          distance: 2.1
        }
      ]

      return {
        success: true,
        data: {
          hospitals: mockHospitals,
          total: mockHospitals.length,
          page: parseInt(params.page) || 1,
          limit: parseInt(params.limit) || 10
        },
        message: '网络异常，显示模拟数据',
        isMockData: true
      }
    }
  }

  // 获取科室列表
  async getDepartments(params = {}) {
    try {
      const response = await get('/v1/appointment/departments', params)
      return response
    } catch (error) {
      console.warn('获取科室列表失败，使用Mock数据:', error)
      
      const mockDepartments = [
        { 
          id: 'd001', 
          hospitalId: params.hospitalId || 'h001', 
          name: '内科', 
          description: '内科疾病诊治', 
          doctorCount: 15, 
          availableSlots: 20 
        },
        { 
          id: 'd002', 
          hospitalId: params.hospitalId || 'h001', 
          name: '外科', 
          description: '外科手术及治疗', 
          doctorCount: 12, 
          availableSlots: 15 
        },
        { 
          id: 'd003', 
          hospitalId: params.hospitalId || 'h001', 
          name: '妇产科', 
          description: '妇科及产科诊疗', 
          doctorCount: 8, 
          availableSlots: 18 
        },
        { 
          id: 'd004', 
          hospitalId: params.hospitalId || 'h001', 
          name: '儿科', 
          description: '儿童疾病诊疗', 
          doctorCount: 10, 
          availableSlots: 25 
        }
      ]

      return {
        success: true,
        data: mockDepartments,
        message: '网络异常，显示模拟数据',
        isMockData: true
      }
    }
  }

  // 获取医生列表
  async getDoctors(params = {}) {
    try {
      const response = await get('/v1/appointment/doctors', params)
      return response
    } catch (error) {
      console.warn('获取医生列表失败，使用Mock数据:', error)
      
      const mockDoctors = [
        {
          id: 'doc001',
          departmentId: params.departmentId || 'd001',
          name: '张明华',
          title: '主任医师',
          specialty: '心血管内科',
          experience: '15年',
          avatar: 'https://api.multiavatar.com/zhang.svg',
          rating: 4.8,
          price: 50
        },
        {
          id: 'doc002',
          departmentId: params.departmentId || 'd001',
          name: '李晓红',
          title: '副主任医师',
          specialty: '消化内科',
          experience: '12年',
          avatar: 'https://api.multiavatar.com/li.svg',
          rating: 4.6,
          price: 40
        },
        {
          id: 'doc003',
          departmentId: params.departmentId || 'd002',
          name: '王建军',
          title: '主任医师',
          specialty: '普外科',
          experience: '18年',
          avatar: 'https://api.multiavatar.com/wang.svg',
          rating: 4.9,
          price: 60
        }
      ]

      return {
        success: true,
        data: mockDoctors,
        message: '网络异常，显示模拟数据',
        isMockData: true
      }
    }
  }

  // 获取时间段
  async getTimeSlots(params = {}) {
    try {
      const response = await get('/v1/appointment/slots', params)
      return response
    } catch (error) {
      console.warn('获取时间段失败，使用Mock数据:', error)
      
      // 生成模拟时间段
      const mockSlots = [
        { time: '08:00-08:30', available: true, price: 50 },
        { time: '08:30-09:00', available: true, price: 50 },
        { time: '09:00-09:30', available: false, reason: '已预约' },
        { time: '09:30-10:00', available: true, price: 50 },
        { time: '10:00-10:30', available: true, price: 50 },
        { time: '14:00-14:30', available: true, price: 50 },
        { time: '14:30-15:00', available: true, price: 50 },
        { time: '15:00-15:30', available: false, reason: '已预约' },
        { time: '15:30-16:00', available: true, price: 50 },
        { time: '16:00-16:30', available: true, price: 50 }
      ]

      return {
        success: true,
        data: mockSlots,
        message: '网络异常，显示模拟数据',
        isMockData: true
      }
    }
  }

  // 显示网络异常提示
  static showNetworkTip() {
    uni.showModal({
      title: '网络提示',
      content: '当前无法连接服务器，正在使用模拟数据。\n\n要使用真实数据，请：\n1. 检查网络连接\n2. 确认服务器运行\n3. 切换到本地开发模式',
      confirmText: '知道了',
      showCancel: false
    })
  }

  // 创建预约
  async createAppointment(appointmentData) {
    try {
      const response = await post('/v1/appointment/orders', appointmentData)
      return response
    } catch (error) {
      console.warn('创建预约失败，使用Mock模拟成功:', error)
      
      const mockAppointment = {
        id: `mock_${Date.now()}`,
        userId: 'mock_user',
        hospitalId: appointmentData.hospitalId,
        hospitalName: appointmentData.hospitalName,
        departmentId: appointmentData.departmentId,
        departmentName: appointmentData.departmentName,
        doctorId: appointmentData.doctorId,
        doctorName: appointmentData.doctorName,
        appointmentDate: appointmentData.appointmentDate,
        timeSlot: appointmentData.timeSlot,
        status: 'confirmed',
        price: appointmentData.price || 50,
        queueNumber: Math.floor(Math.random() * 20) + 1,
        createTime: new Date().toISOString(),
        patientInfo: appointmentData.patientInfo || {
          name: '张三',
          phone: '138****5678'
        }
      }
      
      return {
        success: true,
        data: { appointment: mockAppointment },
        message: '网络异常，模拟预约成功',
        isMockData: true
      }
    }
  }

  // 获取我的预约列表
  async getMyAppointments(params = {}) {
    try {
      const response = await get('/v1/appointment/orders', params)
      return response
    } catch (error) {
      console.warn('获取预约列表失败，使用Mock数据:', error)
      
      const mockAppointments = [
        {
          id: 'mock_001',
          userId: 'mock_user',
          hospitalId: 'h001',
          hospitalName: '河北省保定市莲池区保定市第一医院',
          departmentId: 'd001',
          departmentName: '内科',
          doctorId: 'doc001',
          doctorName: '张明华',
          appointmentDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          timeSlot: '09:00-09:30',
          status: 'confirmed',
          price: 50,
          queueNumber: 8,
          createTime: new Date().toISOString(),
          patientInfo: { name: '张三', phone: '138****5678' }
        }
      ]
      
      return {
        success: true,
        data: {
          appointments: mockAppointments,
          total: mockAppointments.length
        },
        message: '网络异常，显示模拟数据',
        isMockData: true
      }
    }
  }

  // 取消预约
  async cancelAppointment(appointmentId) {
    try {
      const response = await del(`/v1/appointment/orders/${appointmentId}`)
      return response
    } catch (error) {
      console.warn('取消预约失败:', error)
      return {
        success: false,
        message: error.message || '取消预约失败',
        isMockData: true
      }
    }
  }

  // 检查是否为Mock数据
  static isMockResponse(response) {
    return response && response.isMockData === true
  }
}

// 创建单例实例
const appointmentService = new AppointmentService()

export default appointmentService

// 导出常用方法
export const {
  checkApiConnectivity,
  getHospitals,
  getDepartments,
  getDoctors,
  getTimeSlots,
  createAppointment,
  getMyAppointments,
  cancelAppointment
} = appointmentService